﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Dynamic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization.Json;
using System.Text;

/// <summary>
/// WebAPI访问
/// </summary>
namespace MDK.Common
{
    public static class WebApiProxyHelper
    {

        public static string StructureUrl(string Ip, string Port, string ControlAction)
        {
            return string.Format("http://{0}:{1}/{2}", Ip, Port, ControlAction);
        }

        /// <summary>
        /// Post
        /// </summary>
        public static bool Post<T>(string url, T model)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, model);
            ms.Seek(0, SeekOrigin.Begin);
            HttpContent content = new StreamContent(ms);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            var client = new HttpClient();
            var resp = client.PostAsync(url, content).Result;
            return resp.IsSuccessStatusCode;
        }

        /// <summary>
        /// Post
        /// </summary>
        public static bool PostAndReturn<T>(string url, ref T model)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, model);
            ms.Seek(0, SeekOrigin.Begin);
            HttpContent content = new StreamContent(ms);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            var client = new HttpClient();
            var resp = client.PostAsync(url, content).Result;
            var respContent = resp.Content.ReadAsStringAsync().Result;
            model = JsonConvert.DeserializeObject<T>(respContent);
            return resp.IsSuccessStatusCode;
        }

        public static bool SaveToAtm(this Bitmap bmp, string url)
        {
            try
            {
                var req = (HttpWebRequest)WebRequest.Create(url + "upload");
                req.Method = "POST";
                req.ContentType = "application/octet-stream";
                var istream = req.GetRequestStream();
                bmp.Save(istream, ImageFormat.Png);
                istream.Flush();
                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
                resp.Close();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}
